package com.aysafety.iotdataplatformclient.configurer;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

@Component
public class IotDataPlatformClient {

    @Autowired
    IotDataPlatformClientInitializer iotDataPlatformClientInitializer;

    private Logger logger = LoggerFactory.getLogger(IotDataPlatformClient.class);

    private String host;
    private int port;

    public void setParams(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public void sendData(Map<String, Object> sendData) {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group).channel(NioSocketChannel.class);
            bootstrap.option(ChannelOption.TCP_NODELAY, true);
            bootstrap.handler(iotDataPlatformClientInitializer);
            Channel channel = bootstrap.connect(this.host, this.port).sync().channel();
            String msg = JSON.toJSONString(sendData, SerializerFeature.WriteMapNullValue);
            msg = msg + "\n";
            channel.writeAndFlush(msg).addListener(ChannelFutureListener.CLOSE);
            channel.closeFuture().sync();
        } catch (Exception e) {
            logger.error("IotDataPlatformClient:", e);
        } finally {
            group.shutdownGracefully();
        }
    }
}
